<?php
namespace app\api\controller;

use app\common\helper\CurlHelper;
use app\common\model\User;

use app\common\validate\UserValidate;
use Exception;
use think\exception\PDOException;
use think\facade\Cache;
use think\Request;
use think\response\Json;
use app\common\model\SysConfig;

use app\common\service\WxService;
class AuthController extends Controller {
    protected $authExcept = [
        'wxlogin', 'wxlogin_dl'
    ];

    protected $wxService;

    public function __construct() {
        parent::__construct();
        $this->wxService = new WxService(SysConfig::get('website', 'APPID'), SysConfig::get('website', 'APP_SECRET'));
    }

    /**
     * 检查用户微信小程序是否注册
     * @param Request $request
     * @param User $fumodel
     * @return Json
     */
    public function wxlogin_dl(Request $request,User $fumodel): Json
    {
        $param = $request->param();
        $code =$param['code']??'';
        $encryptedData='';
        $iv='';
        $user_info = $this->wxService->getOpenId($code, $encryptedData, $iv);
        if (!$user_info['openid']) {
            return client_error('授权失败');
        }
        $where['openid'] = array('EQ',$user_info['openid']);
        $userinfo = $fumodel->field('id,avatar,nickname,openid')->where($where)->find();
        if(!$userinfo){
            return client_error('授权失败');
        }
        $data['avatar']=$userinfo['avatar'];
        $data['nickName']=$userinfo['nickname'];
        return success($data);
    }

    /**
     * 微信小程序登录并发放token
     * @param Request $request
     * @param User $fumodel
     * @return Json
     * @throws PDOException
     * @throws Exception
     */
    public function wxlogin(Request $request,User $fumodel)
    {
        $param = $request->param();
        $avatar = $param['avatar'] ?? '';
        $nickname = $param['nickname'] ?? '';
        $code = $param['code'] ?? '';
        $user_type = $param['user_type'] ?? 'default';
        $uid = $param['uid'] ?? '0';
        $birthday = $param['birthday'] ?? '0';
        $mark = $param['mark'] ?? '';
        $phone = $param['phone'] ?? '';
        $encryptedData = $param['encryptedData'] ?? '';
        $iv = $param['iv'] ?? '';
        if(!$avatar || !$nickname || !$code){
            return error('参数不足');
        }
        // $token = $this->getToken(1);
        // $uid=Crypt::encrypt(1);
        // return success(['token' => $token,'uid'=>$uid], '登录成功');
        $APPID = SysConfig::get('website', 'APPID');
        $APP_SECRET = SysConfig::get('website', 'APP_SECRET');
        $user_info = $this->wxService->getOpenId($code, $encryptedData, $iv);
        if (!$user_info['openid']) {
            return error('授权失败');
        }
        $where['openid'] = array('EQ',$user_info['openid']);
        $tel= $user_info['tel'] ?? '';
        if($tel){
            $where['mobile'] = array('EQ',$tel);
        }
        $userinfo = $fumodel->field('id,avatar,nickname,openid')->where($where)->find();
        //登录逻辑
        // 启动事务
        $fumodel->startTrans();
        try {
            if($userinfo){
                $data_login['login_ip']=$request->ip();
                $data_login['last_time']=time();
                $data_login['nickname']=$nickname;
                $data_login['avatar']=$avatar;
                if(!$userinfo['distribution_mnp_qr_code']){
                    $data_login['distribution_mnp_qr_code']=$this->wxService->getXcxCode($APPID,$APP_SECRET,$userinfo['distribution_code']);
                }
                $lat= $param['lat'] ?? '';
                if($lat){
                    $data_login['latitude']=$lat;
                    $data_login['longitude']=$param['lng'];
                }
                $fumodel->where('id', $userinfo['id'])->update($data_login);
                $token = $this->getToken($userinfo['id']);
                $uid=$userinfo['id'];
                $fumodel->commit();
                return success(['token' => $token, 'uid' => $uid, 'code' => $userinfo['distribution_code'], 'user_info' => $userinfo], '登录成功');
            }
//            $res['sn'] =$userinfo['sn']=create_user_sn();
//            $res['distribution_code']=$userinfo['nickname']=generate_invite_code();
            $res['nickname']=$userinfo['nickname']=$nickname;
            $res['username']=$userinfo['username'] ='';
            $res['avatar']=$userinfo['avatar'] = $avatar;
            $res['openid'] = $user_info['openid'];
            $res['mobile']=$userinfo['mobile'] = $user_info['tel'];
            $res['type']=$userinfo['type'] =1;
            $res['create_time'] = time();
            $res['login_ip']=$request->ip();
            $res['login_time']=time();
            $lat=$param['lat']??'';
            if($lat){
                $res['latitude']=$lat;
                $res['longitude']=$param['lng'];
            }
            $res['distribution_mnp_qr_code']=$this->wxService->getXcxCode($APPID,$APP_SECRET,$res['distribution_code']);
            $uid=$fumodel->insertGetId($res);

            $fumodel->commit();
        } catch (Exception $e) {
            $fumodel->rollback();
            return client_error($e->getMessage());
        }
        $token = $this->getToken($uid);
        //返回数据
        return success(['token' => $token,'uid'=>$uid,'code'=>$res['distribution_code'],'user_info'=>$userinfo], '注册成功');
    }








}